package com.interview.communication;

/**
 * 【方式2】volatile + synchronized 共享变量
 * 使用volatile保证可见性，synchronized保证原子性
 */
public class SharedVariableExample {

    static class Counter {
        private volatile int count = 0;  // volatile保证对其他线程可见

        synchronized void increment() {
            count++;
        }

        int getCount() {
            return count;
        }
    }

    public static void demo() throws InterruptedException {
        Counter counter = new Counter();

        // 创建10个线程，每个线程对计数器加1000次
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    counter.increment();
                }
                System.out.println(Thread.currentThread().getName() + " 完成");
            });
        }

        // 启动所有线程
        long start = System.currentTimeMillis();
        for (Thread t : threads) {
            t.start();
        }

        // 等待所有线程完成
        for (Thread t : threads) {
            t.join();
        }

        long time = System.currentTimeMillis() - start;
        System.out.println("最终计数: " + counter.getCount() + " (耗时: " + time + "ms)");
    }
}

